package com.wangsh.splider.web.back.intercepor;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSONObject;
import com.wangsh.splider.common.pojo.ApiResponse;
import com.wangsh.splider.common.pojo.ApiResponseEnum;
import com.wangsh.splider.common.pojo.JSONEnum;
import com.wangsh.splider.common.util.ConstatFinalUtil;
import com.wangsh.splider.controller.BaseController;
import com.wangsh.splider.outer.IClientOuterService;
import com.wangsh.splider.users.pojo.AAdmins;
import com.wangsh.splider.users.service.IUsersDbService;

/**
 * 配置拦截器
 * @author Xh-Win10-Server
 */
@Component("authInterceptor")
public class AuthInterceptor extends BaseController implements HandlerInterceptor
{
	/* 管理员的登录网址 */
	private String loginUrl = ConstatFinalUtil.CONFIG_JSON.getString("usersCenter.back.login.url") ; 
	/* 验证token的网址 */
	private String verifyTokenURL = ConstatFinalUtil.CONFIG_JSON.getString("usersCenter.outer.url") ; 
	/* 请求的私钥 */
	private String priKey = ConstatFinalUtil.CONFIG_JSON.getString("private.key");
	@Resource
	private IClientOuterService clientOuterService;
	
	@Resource
	private IUsersDbService usersDbService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		ConstatFinalUtil.SYS_LOGGER.info("--preHandle--");
		
		/* 设置一些公共的变量 */
		this.commonOper(request);
		
		Map<String, String> paramsMap = new HashMap<String, String>();
		HttpSession session = request.getSession();
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		
		if(admins != null)
		{
			return true ; 
		}
		
		//ConstatFinalUtil.SYS_LOG.info("----1 preHandle(执行之后执行) ----");
		String[] tokens = request.getParameterValues("token");
		String token = "" ; 
		if(tokens != null && tokens.length > 0)
		{
			token = tokens[tokens.length - 1]; 
		}
		
		/* 存储数据信息 */
		JSONObject dataReqJSON = new JSONObject();
		try
		{
			if(admins == null && !"".equalsIgnoreCase(token))
			{
				dataReqJSON.put("token", token);
				/* 验证管理员的token */
				JSONObject responseJSON = this.clientOuterService.verifyAdminsTokenService(dataReqJSON);
				
				if(responseJSON != null && responseJSON.getInteger("code") == ApiResponseEnum.STATUS_SUCCESS.getStatus())
				{
					//登陆成功
					JSONObject dataJSON = (JSONObject) responseJSON.get("data");
					JSONObject adminsJSON = dataJSON.getJSONObject("admins");
					String id = adminsJSON.get("id") + "";
					String email = adminsJSON.get("email") + "";
					String name = adminsJSON.get("name") + "";
					String lastLoginTime = adminsJSON.get("lastLoginTime") + "";
					
					Map<String, Object> condMap = new HashMap<String, Object>();
					condMap.put("ssoId", id);
					ApiResponse<AAdmins> adminsResponse = this.usersDbService.findOneAdminsService(condMap);
					admins = adminsResponse.getDataOneJava() ; 
					
					if(admins != null)
					{
						admins.setEmail(email);
						admins.setName(name);
						admins.setSsoId(Integer.valueOf(id));
						admins.setUpdateTime(new Date());
						admins.setLastLoginTime(this.dateFormatUtil.strDateTime(lastLoginTime));
						//将令牌放到对象之中
						admins.setTokenStr(token);
						
						this.usersDbService.updateOneAdminsService(admins);
					}else
					{
						admins = new AAdmins();
						admins.setEmail(email);
						admins.setName(name);
						admins.setSsoId(Integer.valueOf(id));
						admins.setStatus(Byte.valueOf("1"));
						admins.setCreateTime(new Date());
						admins.setUpdateTime(new Date());
						admins.setLastLoginTime(this.dateFormatUtil.strDateTime(lastLoginTime));
						//将令牌放到对象之中
						admins.setTokenStr(token);
						
						ApiResponse<Object> apiResponse = this.usersDbService.saveOneAdminsService(admins);
						if(apiResponse.getCode() == ApiResponseEnum.STATUS_SUCCESS.getStatus() )
						{
							Map<String,Object> dataOneMap = apiResponse.getDataOne(); 
							admins.setId(Integer.valueOf(dataOneMap.get(JSONEnum.ID.getName()) + ""));
						}
					}
					
					session.setAttribute("admins", admins);
					return true ; 
				}
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("请求服务器报错了:{}",dataReqJSON,e);
		}
		
		/* 加上returnUrl */
		String returnUrl = request.getRequestURL() + "";
		String queryStr = request.getQueryString() ;
		if(queryStr == null)
		{
			queryStr = "" ; 
		}
		returnUrl += "?" + queryStr ; 
		
		/* 对ReturnUrl进行encode加密 */
		String returnUrlEncode = URLEncoder.encode(returnUrl, "UTF-8");
		
		ConstatFinalUtil.SYS_LOGGER.info("---returnUrl:{}--returnUrlEncode:{}",returnUrl,returnUrlEncode);
		String loginUrl = this.loginUrl + "&returnUrl=" + returnUrlEncode ; 
		response.sendRedirect(loginUrl);
		return false;
	}
}
